#pragma once

#include "log.hpp"

#include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>

#include "Task.hpp"
#include "ThreadPool.hpp"

using namespace std;

namespace server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    static const uint16_t gport = 8080;
    static const int gbacklog = 5;
    class TcpServer;

    class ThreadData
    {
    public:
        ThreadData(TcpServer *self, int sock) : _self(self), _sock(sock)
        {
        }

    public:
        TcpServer *_self;
        int _sock;
    };
    class TcpServer
    {
    public:
        TcpServer(const uint16_t &port = gport) : _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // 创建socket套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "creat socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "creat socket success:%d ",_listensock);

            // 绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success");
            // 设置socket 为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success");
        }
        void start()
        {
            ThreadPool<Task>::getInstance()->run();
            logMessage(NORMAL,"thread init success");
            for (;;)
            {
                // signal (SIGCHLD,SIG_IGN);多进程信号忽略版
                //  获取新链接
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error,next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success,get a new sock:%d",sock);
                cout << "sock:" << sock << endl;
                // 这里就是一个sock，未来通信就用这个sock，面向字节流的，后续全都是文件操作

                // verson1
                //  serviceIO(sock);
                //  close(sock);//对于一个使用完毕的sock，我们必须要关闭这个sock，要不然会导致，文件描述符泄露

                // verson 2 多进程版
                // pid_t id = fork();
                // if (id == 0) // child
                // {
                //     close(_listensock);
                //     //if(fork()>0) exit(0);
                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // father
                // pid_t ret =waitpid(id,nullptr,0);
                // if(ret>0)
                // {
                //     std::cout<<"waitsuccess: "<<ret<<std::endl;
                // }
                // close(sock);

                // verson 3 多线程版
                //  pthread_t tid;
                //  ThreadData* td =new ThreadData(this,sock);
                //  pthread_create(&tid,nullptr,threadRoutine,td);

                // verson4 线程池
                
                ThreadPool<Task>::getInstance()->push(Task(sock,serviceIO));
            }
        }

        // static void *threadRoutine(void *args)
        // {
        //     pthread_detach(pthread_self());
        //     ThreadData *td = static_cast<ThreadData *>(args);
        //     td->_self->serviceIO(td->_sock);
        //     delete td;
        //     close(td->_sock);
        //     delete td;
        //     return nullptr;
        // }

        ~TcpServer()
        {
        }

    private:
        int _listensock; // 不用来数据通信，用来监听，获取新链接
        uint16_t _port;
    };
}